package com.jw.elasticsearch.springboot.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsClientConfig {

    @Value("${local.elastic.username}")
    private String userName;
    @Value("${local.elastic.password}")
    private String password;
    @Value("${local.elastic.client.host}")
    private String clientHost;
    @Value("${local.elastic.client.port}")
    private int clientPort;

    @Bean(name = "restHighLevelClient")
    public RestHighLevelClient getConnection() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(clientHost, clientPort, HttpHost.DEFAULT_SCHEME_NAME)
                ).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    // es有密码时添加此配置
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        httpClientBuilder.disableAuthCaching();
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                })
        );
    }
}
